<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Adapter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Digest.php 23775 2011-03-01 17:25:24Z ralph $
 */


/**
 * @see Ext_Auth_Adapter_Ucenter
 */
require_once 'Ext/Auth/Adapter/Ucenter.php';

/**
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Adapter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Ext_Auth_Adapter_Extension_Ucenter extends Ext_Auth_Adapter_Ucenter
{

    /**
     * Defined by Zend_Auth_Adapter_Interface
     *
     * @throws Zend_Auth_Adapter_Exception
     * @return Zend_Auth_Result
     */
    public function authenticate()
    {     
        $_result = parent::authenticate();

    	$result = array(
            'code'  	=> $_result->getCode(),
            'identity' 	=> $_result->getIdentity(),
            'messages' 	=> $_result->getMessages()
		);

    	$_appModelDbTableUser = new App_Model_DbTable_User();
    	if ($_result->isValid()) 
    	{
    		$username = $_result->getIdentity();
    		
    		$_appModelDbTableAccountSelf = new App_Model_DbTable_Account_Self();
			$accountSelfRow = $_appModelDbTableAccountSelf->getRow($username);
			if(isset($accountSelfRow['userId']) && $accountSelfRow['userId'] > 0)
			{
				$userId = $accountSelfRow['userId'];
			}
			else
			{
				$_appModelDbTableUser = new App_Model_DbTable_User();
				$row = array(
	    			'nickname'	=> $username,
	    		);
	    		$userId = $_appModelDbTableUser->addNew($row);

	    		if(!$accountSelfRow)
	    		{
					$row = array(
		    			'username'	=> $username,
		    			'email'		=> $email,
		    			'userId'	=> $userId,
		    		);
		    		$_appModelDbTableAccountSelf->addNew($row);
	    		}
	    		else 
	    		{
					$row = array(
		    			'userId'	=> $userId,
		    		);
		    		$_appModelDbTableAccountSelf->addOld($row, $username);
	    		}
			}
			$result['identity'] = $userId;
    	}
    	
    	return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']);
    }
    
    
}
